# Windows进程和网络查询Makefile

# 默认参数配置
SEARCH_PORT := 8004

# 首先创建PowerShell脚本文件
.PHONY: init
init:
	@echo 'function Get-PortPid { param([int]$$port); $$result = netstat -ano | Select-String ":$$port"; if ($$result) { $$portPid = $$result.ToString().Split()[-1]; return $$portPid } else { return $$null } }' > port-utils.ps1
	@echo 'function Show-PortInfo { param([int]$$port); $$result = netstat -ano | Select-String ":$$port"; if ($$result) { return $$result } else { return "No process found using port $$port" } }' >> port-utils.ps1
	@echo 'function Kill-PortProcess { param([int]$$port); $$portPid = Get-PortPid $$port; if ($$portPid) { $$proc = Get-Process -Id $$portPid -ErrorAction SilentlyContinue; if ($$proc) { Write-Host "Process information:"; $$proc | Format-Table Id, ProcessName, Path -AutoSize; Stop-Process -Id $$portPid -Force; Write-Host "Process terminated" } else { Write-Host "Cannot find process with ID $$portPid" } } else { Write-Host "No process found using port $$port" } }' >> port-utils.ps1

# 查询端口监听状态
.PHONY: get-pid
get-pid: init
	@echo "Port query for port $(SEARCH_PORT):"
	@powershell -NoProfile -ExecutionPolicy Bypass -Command ". .\port-utils.ps1; Show-PortInfo $(SEARCH_PORT)"


# 关闭指定端口对应的进程
.PHONY: kill-port
kill-port: init
	@echo "Killing process using port $(SEARCH_PORT) without confirmation..."
	@powershell -NoProfile -ExecutionPolicy Bypass -Command ". .\port-utils.ps1; Kill-PortProcess $(SEARCH_PORT)"

# 清理临时文件
.PHONY: clean
clean:
	@del port-utils.ps1 2>NUL || echo No temporary files to clean

# 显示帮助信息
.PHONY: help
help:
	@echo "Windows Process and Network Query Makefile"
	@echo "Usage:"
	@echo "  make get-pid   - Query port $(SEARCH_PORT) status -about pid"
	@echo "  make kill-port  - Kill process using port $(SEARCH_PORT) without confirmation"
	@echo "  make clean      - Remove temporary files"
	@echo "  make help       - Show this help"

# 默认目标
.PHONY: default
default: help